package com.example.springai.controller;

import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.io.IOException;

@RestController
@RequestMapping("/wechat")
public class WeChatController {

    @Resource
    private WxMpService wxMpService;

    @Resource
    private WxMpMessageRouter messageRouter;

    // 验证接口
    @GetMapping("/callback")
    public String authGet(@RequestParam("signature") String signature,
                          @RequestParam("timestamp") String timestamp,
                          @RequestParam("nonce") String nonce,
                          @RequestParam("echostr") String echostr) {
        if (wxMpService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return "非法请求";
    }

    // 接收消息
    @PostMapping(value = "/callback", consumes = {MediaType.APPLICATION_XML_VALUE, "text/xml"}, produces = MediaType.APPLICATION_XML_VALUE)
    public String post(@RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce) throws IOException {
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            return "非法请求";
        }

        WxMpXmlMessage wxMessage = WxMpXmlMessage.fromXml(requestBody);
        final WxMpXmlOutMessage outMessage = messageRouter.route(wxMessage);
        return outMessage == null ? "" : outMessage.toXml();
    }
}